//
//  FocusPicBLL.m
//  LZMusicPlayer
//
//  Created by wulanzhou on 2016/11/2.
//  Copyright © 2016年 wulanzhou. All rights reserved.
//

#import "FocusPicBLL.h"
#import "BMAFocus.h"
#import "BMAResponse.h"
#import "CacheDataUtil.h"
#import "FocusPic.h"

#define kCacheFocusPicKey @"kCacheFocusPicKey"

@interface FocusPicBLL (){

    NSArray *_picTitles;
    NSArray *_picURLs;
    NSArray *_allPics;
}

@end


@implementation FocusPicBLL

@synthesize titles=_picTitles;
@synthesize imageURLs=_picURLs;

- (NSArray *)titles{

    if (!_picTitles) {
        NSArray *arr=[CacheDataUtil unarchiveValueForKey:kCacheFocusPicKey];
        if (arr&&[arr count]>0) {
            _picTitles=[arr valueForKeyPath:@"randpic_desc"];
        }
    }
    return _picTitles;
}

- (NSArray *)imageURLs{
    if (!_picURLs) {
        NSArray *arr=[CacheDataUtil unarchiveValueForKey:kCacheFocusPicKey];
        if (arr&&[arr count]>0) {
            _picURLs=[arr valueForKeyPath:@"randpic"];
        }
    }
    return _picURLs;
}

- (void)loadFocus:(void (^) ())completion{

    BMAFocus *request=[[BMAFocus alloc] init];
    __weak BMAFocus *_WSELF=request;
    [request setCZRequestURL:^NSString *{
        return [_WSELF focusPic:5];
    }];
    
    [request starWithFinishedBlock:^(NSError *error, id result) {
        BMAResponse *respose=[[BMAResponse alloc] initWithDictionary:result error:error];
        if (respose.success) {
            //DLog(@"请求成功 =%@",respose.result);
            
            NSArray *arr=[respose.result objectForKey:@"pic"];
            _allPics=[FocusPic mj_objectArrayWithKeyValuesArray:arr];
            [CacheDataUtil setValueArchiver:_allPics forKey:kCacheFocusPicKey];
            if(_allPics&&[_allPics count]>0){
                _picTitles=[_allPics valueForKeyPath:@"randpic_desc"];
                _picURLs=[_allPics valueForKeyPath:@"randpic"];
            }
            
        }else{
            DLog(@"请求失败 =%@",respose.error_msg);
        }
        
        if (completion) {
            completion();
        }
    }];
}

- (NSString *)linkItemAtIndex:(NSInteger)index{

    if (_allPics&&[_allPics count]>0) {
        FocusPic *item=[_allPics objectAtIndex:index];
        if ([item hasLink]) {
            return item.code;
        }
    }
    
    NSArray *arr=[CacheDataUtil unarchiveValueForKey:kCacheFocusPicKey];
    if (arr&&[arr count]>0) {
        FocusPic *item=[arr objectAtIndex:index];
        if ([item hasLink]) {
            return item.code;
        }
    }
    
    return nil;
    
}

@end
